package msg;

import org.apache.log4j.Logger;
import use.FileUse;
import util.ApplyUtil;

import java.util.Arrays;
import java.util.Map;

public class MsgHandle {
    private static MsgHandle instance;
    private Logger logger = Logger.getLogger(MsgManager.class);
    public static MsgHandle getInstance() {
        if (instance == null) {
            instance = new MsgHandle();
        }
        return instance;
    }

    void msg_switch(String msg){
        logger.info("recv:" + msg);
        Map<String,String> map = ApplyUtil.toMap(msg);
        if(map.get("command_id") == null){
            logger.info(String.format("command_id 为 null :%s" ,msg));
            return;
        }
        switch (map.get("command_id")){
            case "90000"://写入文件
                command_90000(map);
                break;
            case "90001"://删除文件
                command_90001(map);
                break;
            case "90002"://读取默认升级文件存放目录的文件名
                command_90002(map);
                break;
            case "90003"://读取升级文件存放目录文件列表
                command_90003(map);
                break;
            default:
                logger.info(String.format("无效command_id:%s" ,msg));
        }
    }
    private void command_90000(Map<String, String> map){
        String[] str = map.get("content").replaceAll("[ \\[\\]]","").split(",");
        byte[] content = new byte[str.length];
        for (int i = 0; i < str.length ; i++) {
            content[i] = (byte) (Integer.parseInt(str[i]) &0xFF);
        }
        map.putIfAbsent("directory", "");
        FileUse.getManager().save_file(map.get("directory"),map.get("file_name"),content);
    }

    private void command_90001(Map<String, String> map) {
    }

    private void command_90002(Map<String, String> map){
        MsgManager.getInstance().msg_send_by_queue(map.get("comeback") ,FileUse.getManager().read_file_name());
        logger.info(String.format("中间件读取默认升级文件名:%s" ,FileUse.getManager().read_file_name()));
    }

    private void command_90003(Map<String, String> map) {
        String v = Arrays.toString(FileUse.getManager().read_file_name_all());
        MsgManager.getInstance().msg_send_by_queue(map.get("comeback") ,v );
        logger.info(String.format("中间件读取默认升级文件名:%s" ,v));
    }
}
